package com.hilin.common.common.handler;

import com.hilin.common.common.ReturnCode;
import com.hilin.entity.vo.RespVo;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.util.Objects;

@ConditionalOnProperty(
        prefix = "com.hilin.web",
        name = "outerWrapping",
        havingValue = "true"
)
@RestControllerAdvice
public class ResponseOuterWrappingHandler implements ResponseBodyAdvice {
    @Override
    public boolean supports(final MethodParameter returnType, final Class converterType) {
        NoCovertRespvo noCovertRespvo = returnType.getMethodAnnotation(NoCovertRespvo.class);
        return noCovertRespvo == null;
    }

    @Override
    public Object beforeBodyWrite(final Object body, final MethodParameter returnType, final MediaType selectedContentType, final Class selectedConverterType, final ServerHttpRequest request, final ServerHttpResponse response) {
        if (request.getURI().toString().contains("api-docs")) {
            return body;
        }
        ServletServerHttpResponse serverHttpResponse = (ServletServerHttpResponse) response;
        if (serverHttpResponse.getServletResponse().getStatus() != 200) {
            return body;
        }
        if (Objects.isNull(body)) {
            return ReturnCode.SUCCESS.resp();
        }
        if (body instanceof RespVo) {
            return body;
        }
        return ReturnCode.SUCCESS.respData(body);
    }

}
